package com.sunshine.monitor.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sunshine.monitor.Consts;
import com.sunshine.monitor.MonitorThread;
import com.sunshine.monitor.util.IOUtils;

public class MonitorFilter implements Filter {

	private static final Map<String, Map<String, String>> VALUES = new HashMap<String, Map<String, String>>(
			5);
	static {
		for (String flag : Consts.NAME_FLAGS) {
			VALUES.put(flag, new HashMap<String, String>());
		}
	}
	
	public void init(FilterConfig config) throws ServletException {
		new Timer().schedule(new MonitorThread(), 0);
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String uri = request.getRequestURI();

		if (uri.endsWith(".do")) {
			doDataRequest(request, response);
		} else if (uri.endsWith(".js") || uri.endsWith(".css")
				|| uri.endsWith(".map")) {
			uri = getLast(uri);
			if (uri.endsWith(".js")) {
				uri = "js/" + uri;
			} else if (uri.endsWith(".css")) {
				uri = "css/" + uri;
			} else if (uri.endsWith(".map")) {
				uri = "css/" + uri;
			}
			doResourcerequest(request, response, uri);
		} else {
			uri = getLast(uri);
			doResourcerequest(request, response, uri);
		}
	}

	private void doDataRequest(HttpServletRequest request,
			HttpServletResponse response) {

	}

	private void doResourcerequest(HttpServletRequest request,
			HttpServletResponse response, String uri) throws IOException {
		OutputStream os = response.getOutputStream();
		InputStream is = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(uri);
		IOUtils.copy(is, os);
		IOUtils.closeStream(is);
	}

	public void destroy() {

	}

	private String getLast(String uri) {
		if (uri != null) {
			int lastIndex = uri.lastIndexOf("/");
			return uri.substring(lastIndex + 1);
		}
		return uri;
	}

}
